<template>
    <div class="article-list-container">
        <!-- 搜索栏 -->
        <el-card class="search-card">
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="标题">
                    <el-input v-model="searchForm.title" placeholder="请输入文章标题" clearable />
                </el-form-item>
                <el-form-item label="分类">
                    <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
                        <el-option label="技术" value="tech" />
                        <el-option label="生活" value="life" />
                        <!-- 可以根据实际分类添加更多选项 -->
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                        <el-option label="已发布" value="published" />
                        <el-option label="草稿" value="draft" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 文章列表 -->
        <el-card class="list-card">
            <template #header>
                <div class="card-header">
                    <span>文章列表</span>
                    <el-button type="primary" @click="handleAdd">新增文章</el-button>
                </div>
            </template>

            <el-table v-loading="loading" :data="articleList" style="width: 100%">
                <el-table-column prop="title" label="标题" min-width="180" show-overflow-tooltip />
                <el-table-column prop="category" label="分类" width="100" />
                <el-table-column prop="summary" label="简介" min-width="300" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ row.summary || (row.content ? row.content.slice(0, 100) + '...' : '暂无简介') }}
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180">
                    <template #default="{ row }">
                        {{ new Date(row.createTime).toLocaleString() }}
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="row.status === 'published' ? 'success' : 'info'">
                            {{ row.status === 'published' ? '已发布' : '草稿' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
                        <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.pageSize"
                    :total="pagination.total" :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../../../utils/requestLogin'

const router = useRouter()
const loading = ref(false)
const articleList = ref([])

// 在 script 开始处添加这个接口
interface SearchForm {
    title: string;
    category: string;
    status: string;
}

// 搜索表单
const searchForm = reactive<SearchForm>({
    title: '',
    category: '',
    status: ''
})

// 分页配置
const pagination = reactive({
    page: 1,
    pageSize: 10,
    total: 0
})

// 获取文章列表
const fetchArticles = async () => {
    loading.value = true
    try {
        const params: Record<string, any> = {
            page: pagination.page,
            pageSize: pagination.pageSize
        }

        if (searchForm.title) {
            params.title = searchForm.title
        }
        if (searchForm.category) {
            // 将英文分类转换为中文
            const categoryMap: Record<string, string> = {
                'life': '生活',
                'tech': '技术',
                'other': '其他'
            }
            params.category = categoryMap[searchForm.category] || searchForm.category
        }
        if (searchForm.status) {
            params.status = searchForm.status
        }

        const response = await request.get('http://cylyxsz.w1.luyouxia.net/blog/api/articles', {
            params,
            paramsSerializer: {
                indexes: null
            }
        })

        // 根据实际返回的数据结构 {"code":200,"message":"success","data":{"total":0,"list":[]}}
        if (response.code === 200) {
            articleList.value = response.data.list // 使用 response.data.list 作为文章列表
            pagination.total = response.data.total // 使用 response.data.total 作为总数
        } else {
            ElMessage.error(response.message || '获取文章列表失败')
        }
    } catch (error) {
        console.error('获取文章列表失败:', error)
        ElMessage.error('获取文章列表失败')
    } finally {
        loading.value = false
    }
}

// 搜索
const handleSearch = () => {
    pagination.page = 1
    fetchArticles()
}

// 重置搜索
const resetSearch = () => {
    (Object.keys(searchForm) as Array<keyof typeof searchForm>).forEach(key => {
        searchForm[key] = ''
    })
    pagination.page = 1
    fetchArticles()
}

// 分页处理
const handleSizeChange = (val: number) => {
    pagination.pageSize = val
    fetchArticles()
}

const handleCurrentChange = (val: number) => {
    pagination.page = val
    fetchArticles()
}

// 新增文章
const handleAdd = () => {
    router.push('/admin/article/edit')
}

// 编辑文章
const handleEdit = (row: any) => {
    console.log(row)
    router.push(`/admin/article/edit/${row.id}`)
}

// 删除文章
const handleDelete = (row: any) => {
    ElMessageBox.confirm('确定要删除这篇文章吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await request.delete(`http://cylyxsz.w1.luyouxia.net/blog/api/articles/${row.id}`)
            ElMessage.success('删除成功')
            fetchArticles()
        } catch (error) {
            console.error('删除文章失败:', error)
            ElMessage.error('删除文章失败')
        }
    }).catch(() => { })
}

onMounted(() => {
    fetchArticles()
})
</script>

<style scoped>
.article-list-container {
    width: 100%;
    height: 100%;
    padding: 20px;
}

.search-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

:deep(.el-select) {
    width: 160px;
    /* 调整选择框的宽度 */
}

:deep(.el-input) {
    width: 200px;
    /* 调整输入框的宽度 */
}

/* 响应式布局 */
@media screen and (max-width: 768px) {

    :deep(.el-select),
    :deep(.el-input) {
        width: 100%;
        /* 在移动端使用全宽 */
    }

    .search-form {
        flex-direction: column;
        gap: 15px;
    }

    .search-form .el-form-item {
        margin-bottom: 0;
        width: 100%;
    }
}
</style>